package cn.dujc.superkid.fragment.MyLessonVideo;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import cn.dujc.core.ui.BaseFragment;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.activities.AnalysisActivity;
import cn.dujc.superkid.activities.CourseVideoActivity;
import cn.dujc.superkid.adapter.ExerciseAdapter;
import cn.dujc.superkid.adapter.UnitTestAdapter;
import cn.dujc.superkid.adapter.UnitTestResultAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.ExercisesPostResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.ResultsEntity;
import cn.dujc.superkid.bean.UnitResult;
import cn.dujc.superkid.bean.VideoListResult;
import cn.dujc.superkid.utils.Preferences;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ExercisesFragment extends BaseFragment implements ExerciseAdapter.OnItemViewClickListener, View.OnClickListener, UnitTestAdapter.OnItemViewClickListener, UnitTestResultAdapter.OnItemClickListener {
    private RecyclerView recyclerView_ercercise;
    private RecyclerView fragment_ex_recycler;
    private final String TAG = ExercisesFragment.class.getName();
    private List<VideoListResult.ExercisesEntity> mList = new ArrayList<>();
    private ExerciseAdapter mAdapter;
    private UnitTestResultAdapter testResultAdapter;
    private Button submitBtn;
    private TextView nodataText;
    private TextView tv_title_0;
    private TextView tv_info;
    private TextView tv_title_2;
    @Override
    public int getViewId() {
        return R.layout.fragment_exercises;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        tv_info= (TextView) findViewById(R.id.tv_info);
        tv_title_0= (TextView) findViewById(R.id.tv_title_0);
        tv_title_2= (TextView) findViewById(R.id.tv_title_2);
        submitBtn = (Button) findViewById(R.id.fragment_exercises_submit_btn);
        submitBtn.setOnClickListener(this);
        nodataText = (TextView) findViewById(R.id.fragment_exercies_no_data);
        testResultAdapter = new UnitTestResultAdapter(mActivity);
        testResultAdapter.setOnItemClickListener(new UnitTestResultAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                Intent intent =new Intent(mActivity,AnalysisActivity.class);
                intent.putExtra("title",mAdapter.getList().get(pos).getExercises_title());
                intent.putExtra("content",mAdapter.getList().get(pos).getExplain_ex());
                startActivity(intent);
            }
        });
        fragment_ex_recycler = (RecyclerView) findViewById(R.id.fragment_ex_recycler);
        fragment_ex_recycler.setLayoutManager(new LinearLayoutManager(mActivity));
        fragment_ex_recycler.setAdapter(testResultAdapter);
        if (bundle != null) {
            mList = bundle.getParcelableArrayList("list");
            if (mList == null || mList.size() == 0) {
                submitBtn.setVisibility(View.GONE);
                nodataText.setVisibility(View.VISIBLE);
            } else {
                submitBtn.setVisibility(View.VISIBLE);
                nodataText.setVisibility(View.GONE);
            }
            recyclerView_ercercise = (RecyclerView) findViewById(R.id.exercise_recyclerview);
            mAdapter = new ExerciseAdapter(mActivity);
            recyclerView_ercercise.setAdapter(mAdapter);
            mAdapter.setList(mList);
            mAdapter.setOnItemViewClickListener(this);
            recyclerView_ercercise.setNestedScrollingEnabled(false);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView_ercercise.setLayoutManager(linearLayoutManager);
            //分割线
            recyclerView_ercercise.addItemDecoration(new DividerItemDecoration(this.getActivity(), linearLayoutManager.getOrientation()));
        }

    }

    private void addGoodQuestion(int pos) {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(getActivity());
        HttpHelper.getCourse().videoGoodQuestion(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(getActivity()).getChannel_id())
                .put("exercises_id", mList.get(pos).getId())
                .put("logincode", loginResult.getLogincode())
                .put("type_id", 1)
                .create()).enqueue(new ResultCallBack<Result<Object>>(getActivity()) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                ToastUtil.showToast(getActivity(), body.getMsg());
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                if(code==400){
                    ToastUtil.showToast(mActivity, msg);
                }else{
                    ToastUtil.showToast(mActivity, "未能读取数据，因为它的格式不正确");
                }
            }
        });
    }

    //校验  是否有题没有答
    private void submitTest() {
        for (int i = 0; i < mAdapter.getList().size(); i++) { //校验是否有题没填写答案
            if (TextUtils.isEmpty(mAdapter.getList().get(i).getValue())) {
                ToastUtil.showToast(mActivity, "第" + (i + 1) + "题没答");
                return;
            }
        }
        requestSubmit();
    }

    private void requestSubmit() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(getActivity());
        HttpHelper.getCourse().videoExercisesPost(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(getActivity()).getChannel_id())
                .put("answer", mAdapter.getValue())
                .put("logincode", loginResult.getLogincode())
                .put("video_id", ((CourseVideoActivity) mActivity).video_id)
                .create()).enqueue(new ResultCallBack<Result<ExercisesPostResult>>(getActivity()) {
            @Override
            public void onSuccessCallback(int code, Result<ExercisesPostResult> body) {
                ToastUtil.showToast(getActivity(), body.getMsg());
                setTestResultData(body.getData());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_exercises_submit_btn:
                submitTest();
                break;
        }
    }

    @Override
    public void onItemViewClick(View v, int pos) {
        if (v.getId() == R.id.item_exercises_add) {
            addGoodQuestion(pos);
        }else{
            Intent intent =new Intent(mActivity,AnalysisActivity.class);
            intent.putExtra("title",mAdapter.getList().get(pos).getExercises_title());
            intent.putExtra("content",mAdapter.getList().get(pos).getExplain_ex());
            startActivity(intent);
        }
    }

    public void setTestResultData(ExercisesPostResult testResultData) {
        tv_title_0.setText(testResultData.getPage_info().getCourses_title());
        tv_title_2.setText("总答题人数0人，回答情况如下");
        String num=testResultData.getPage_info().getNum()+"";
        String first=testResultData.getPage_info().getFirst_score()+"";
        String current=testResultData.getPage_info().getTotal_score()+"";
        tv_info.setText("本试卷共"+num+"题，共计100分，第一次得分为"+first+"分，本次得分"+current);
        hideTest();
        List<UnitResult.DataBean.ResultsBean> list = new ArrayList<>();
        for (ResultsEntity resultsEntity : testResultData.getResults()) {
            list.add(new UnitResult.DataBean.ResultsBean(resultsEntity.getNum(),
                    Integer.parseInt(resultsEntity.getUser()),
                    Integer.parseInt(resultsEntity.getAnswerRight()),
                    Double.parseDouble(resultsEntity.getCorrectRate()),
                    resultsEntity.getUserAnswer(),
                    resultsEntity.getRow(),
                    Integer.parseInt(resultsEntity.getAnalysis())));
        }
        testResultAdapter.setDatas(list);
    }

    private void hideTest() {
        recyclerView_ercercise.setVisibility(View.GONE);
        submitBtn.setVisibility(View.GONE);
        findViewById(R.id.ex_nested).setVisibility(View.VISIBLE);
    }

    @Override
    public void onItemClick(int pos) {
        Intent intent =new Intent(mActivity, AnalysisActivity.class);
        intent.putExtra("title",mAdapter.getList().get(pos).getExercises_title());
        intent.putExtra("content",mAdapter.getList().get(pos).getExplain_ex());
        startActivity(intent);
    }
}
